const std = @import("std");
const httpz = @import("httpz");
const student_service = @import("../services/student_service.zig");
const student_model = @import("../models/student_model.zig");

fn add(request: *httpz.Request, response: *httpz.Response) !void {
    const student = request.json(student_model.Student) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (student == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    const res = try student_service.add(&student.?);
    try response.json(.{ .result = res }, .{});
}

fn query(request: *httpz.Request, response: *httpz.Response) !void {
    const student = request.json(student_model.Student) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (student == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    try student_service.query(&student.?, response);
}

fn query_by_pk(request: *httpz.Request, response: *httpz.Response) !void {
    const form_data = try request.formData();
    const id_s = form_data.get("id");
    if (id_s == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }
    const id = try std.fmt.parseInt(i32, id_s.?, 10);
    const student = try student_service.query_by_pk(id);
    try response.json(.{ .result = student }, .{});
}

fn update(request: *httpz.Request, response: *httpz.Response) !void {
    const student = request.json(student_model.Student) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (student == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    const res = try student_service.update(&student.?);
    try response.json(.{ .result = res }, .{});
}

fn delete(request: *httpz.Request, response: *httpz.Response) !void {
    const form_data = try request.formData();
    const id_s = form_data.get("id");
    if (id_s == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }
    const id = try std.fmt.parseInt(i32, id_s.?, 10);
    const res = try student_service.delete(id);
    try response.json(.{ .result = res }, .{});
}

pub fn route(router: anytype) void {
    router.post("/student/add", add, .{});
    router.post("/student/query", query, .{});
    router.post("/student/query_by_pk", query_by_pk, .{});
    router.post("/student/update", update, .{});
    router.post("/student/delete", delete, .{});
}
